package com.ruoyi.project.applet.service.impl;

import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.applet.domain.Collect;
import com.ruoyi.project.applet.domain.Url;
import com.ruoyi.project.applet.mapper.CollectMapper;
import com.ruoyi.project.pc.domain.Category;
import com.ruoyi.project.pc.service.impl.CategoryServiceImpl;
import com.ruoyi.project.system.domain.SysUserWx;
import com.ruoyi.project.system.mapper.SysUserWxMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.applet.mapper.GoodMapper;
import com.ruoyi.project.applet.domain.Good;
import com.ruoyi.project.applet.service.IGoodService;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * 商品Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-24
 */
@Service
public class GoodServiceImpl implements IGoodService 
{
    private Logger logger = LoggerFactory.getLogger("GoodServiceImpl");

    @Autowired
    private GoodMapper goodMapper;

    @Autowired
    private SysUserWxMapper sysUserWxMapper;

    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private CategoryServiceImpl categoryService;

    /**
     * 查询商品
     * 
     * @param id 商品ID
     * @return 商品
     */
    @Override
    public Good selectGoodById(String id,String userId)
    {
        Good good = goodMapper.selectGoodById(id);
        Assert.notNull(good,"商品不存在");
        if (StringUtils.hasText(good.getFirstImgUrl())){
            good.setFirstImg(JSONObject.parseArray(good.getFirstImgUrl(), Url.class));
        }
        if (StringUtils.hasText(good.getSecondImgUrl())){
            good.setSecondImg(JSONObject.parseArray(good.getSecondImgUrl(), Url.class));
        }
        Collect collect = new Collect();
        collect.setUserId(userId);
        collect.setGoodId( good.getId());
        //设置收藏状态
        List<Collect> collectList = collectMapper.selectCollectList(collect);
        if (!CollectionUtils.isEmpty(collectList)) {
            good.setCollectStatus("1");
        } else {
            good.setCollectStatus("0");
        }
        return good;
    }

    /**
     * 查询商品列表
     * 
     * @param good 商品
     * @return 商品
     */
    @Override
    public List<Good> selectGoodList(Good good)
    {
        List<Good> goodList = goodMapper.selectGoodList(good);
        for (Good good1 : goodList) {
            if (StringUtils.hasText(good1.getFirstImgUrl())) {
                good1.setFirstImg(JSONObject.parseArray(good1.getFirstImgUrl(), Url.class));
            }
            if (StringUtils.hasText(good1.getSecondImgUrl())) {
                good1.setSecondImg(JSONObject.parseArray(good1.getSecondImgUrl(), Url.class));
            }

        }
        //设置发布用户信息
        List<String> userIdList = goodList.stream().map(Good::getUserId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty( userIdList)) {
            List<SysUserWx> userWxList = sysUserWxMapper.selectSysUserWxByOpenIds(userIdList);
            for (Good good1 : goodList) {
                for (SysUserWx userWx : userWxList) {
                    if (good1.getUserId().equals(userWx.getOpenId())){
                        good1.setUserWx(userWx);
                    }
                }
            }
        }

        return goodList;
    }

    @Override
    public List<Good> selectGoodByIds(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.EMPTY_LIST;
        }

        List<Good> goodList = goodMapper.selectGoodByIds(ids);
        for (Good good1 : goodList) {
            if (StringUtils.hasText(good1.getFirstImgUrl())) {
                good1.setFirstImg(JSONObject.parseArray(good1.getFirstImgUrl(), Url.class));
            }
            if (StringUtils.hasText(good1.getSecondImgUrl())) {
                good1.setSecondImg(JSONObject.parseArray(good1.getSecondImgUrl(), Url.class));
            }

        }
        //设置发布用户信息
        List<String> userIdList = goodList.stream().map(Good::getUserId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty( userIdList)) {
            List<SysUserWx> userWxList = sysUserWxMapper.selectSysUserWxByOpenIds(userIdList);
            for (Good good1 : goodList) {
                for (SysUserWx userWx : userWxList) {
                    if (good1.getUserId().equals(userWx.getOpenId())){
                        good1.setUserWx(userWx);
                    }
                }
            }
        }
        return goodList;
    }

    /**
     * 新增商品
     * 
     * @param good 商品
     * @return 结果
     */
    @Override
    public String insertGood(Good good)
    {
        //申贷、助贷、婚恋三个类目只能发布一条
        List<Category> categoryList = categoryService.selectCategoryList(new Category());
        for (Category category : categoryList) {
            if (category.getId().equals(good.getCategoryId())) {
                if ("申贷".equals(category.getName()) || "助贷".equals(category.getName()) || "婚恋".equals(category.getName())) {
                    Good query = new Good();
                    query.setUserId(good.getUserId());
                    query.setCategoryId(good.getCategoryId());
                    List<Good> goodList = selectGoodList(query);
                    if (!CollectionUtils.isEmpty(goodList)){
                        throw new RuntimeException("该类目只能发布一条");
                    }
                }
            }
        }


        String id = UUID.randomUUID().toString().replace("-","");
        good.setId(id);
        if (good.getFirstImg() != null) {
            good.setFirstImgUrl(JSONObject.toJSONString(good.getFirstImg()));
        }
        if (good.getSecondImg() != null) {
            good.setSecondImgUrl(JSONObject.toJSONString(good.getSecondImg()));
        }
        good.setCreateTime(DateUtils.getNowDate());
        goodMapper.insertGood(good);

        logger.info("用户"+good.getUserId()+"发布商品"+good.getId());
        return id;
    }

    /**
     * 修改商品
     * 
     * @param good 商品
     * @return 结果
     */
    @Override
    public int updateGood(Good good)
    {
        good.setUpdateTime(DateUtils.getNowDate());
        if (good.getFirstImg() != null) {
            good.setFirstImgUrl(JSONObject.toJSONString(good.getFirstImg()));
        }
        if (good.getSecondImg() != null) {
            good.setSecondImgUrl(JSONObject.toJSONString(good.getSecondImg()));
        }
        logger.info("用户"+good.getUserId()+"修改商品"+good.getId());
        return goodMapper.updateGood(good);
    }

    /**
     * 批量删除商品
     * 
     * @param ids 需要删除的商品ID
     * @return 结果
     */
    @Override
    public int deleteGoodByIds(String[] ids)
    {
        return goodMapper.deleteGoodByIds(ids);
    }

    /**
     * 删除商品信息
     * 
     * @param id 商品ID
     * @return 结果
     */
    @Override
    public int deleteGoodById(String id)
    {
        return goodMapper.deleteGoodById(id);
    }
}
